The bookdown package can be installed from CRAN or Github:

install.packages("bookdown")
# or the development version
# devtools::install_github("rstudio/bookdown")

1 Introduction

1.1 Directions to start a book (after downloading packages described)

  1. Open R Studio
  2. File - New Project - New Directory - New Book Project
  3. Save where you think it should be.

1.2 Structure of book

  • There will be multiple Rmd (R Markdown) files - one for each chapter.
  • File naming:
    • index.Rmd
    • 01-yourchapter1title.Rmd
    • 02-yourchapter2title.Rmd
  • Each Rmd file contains one and only one chapter, and a chapter is defined by the first-level heading #.

1.3 Other tips

  • In your _output.yml file: delete “bookdown::pdf_book: includes: in_header: preamble.tex latex_engine: xelatex citation_package: natbib keep_tex: yes” and replace the “bookdown::epub: default” with “bookdown::html_document2: default”

  • In your index.Rmd file, add “always_allow_html: yes” to the options at the top

1.4 PDF

To compile your book to PDF, you need XeLaTeX. You are recommended to install TinyTeX (which includes XeLaTeX): https://yihui.org/tinytex/.

2 Rmd Basics for crafting your document

2.1 Display

2.1.1 Font

  • Italics: _text_ or *text*
  • Bold: __text__ (two underscores) or **text**
  • Subscripts e.g. H2O H~2~O

2.1.2 Blockquotes

Use >

> "To sustainably manage the water resources of California, in cooperation with 
> other agencies, to benefit the state's people and protect, restore, and enhance the
> natural and human environments." 
> 
> --- DWR

“To sustainably manage the water resources of California, in cooperation with other agencies, to benefit the state’s people and protect, restore, and enhance the natural and human environments.”

— DWR

2.1.3 Indent Text

Use |

| Here you can 
|  indent and separate 
|   lines
|    for fun 
|   patterns
|  like
| this 
Here you can
 indent and separate
  lines
   for fun
  patterns
 like
this

2.1.4 Text in a gray block

Enclose in ``` or indent by 4 spaces

``` 
Here is a chunk of code 
```    

Result:

Here is a chunk of code

2.1.5 Equations

Equations
Surround with $

$a^2 + b^2 = c^2$  

\(a^2 + b^2 = c^2\).

Alternatively for a more complicated equation:

\begin{equation} 
  f\left(k\right) = \binom{n}{k} p^k\left(1-p\right)^{n-k}
  (\#eq:binom)
\end{equation} 

(The #eq:binom can be used to reference this equation later)

\[\begin{equation} f\left(k\right) = \binom{n}{k} p^k\left(1-p\right)^{n-k} \tag{2.1} \end{equation}\]

2.2 Organization

2.2.1 Headers:

# Header 1 (Largest)
## Header 2
### Header 3

Header with no numbering:

### Header {-}

2.2.2 Lists:

2.2.2.1 Use *, -, or +

* peas
* apples
* carrots
  * baby
  * large
    * colored
    * orange
  • peas
  • apples
  • carrots
    • baby
    • large
      • colored
      • orange

2.2.2.2 Use numbers:

1. Enter data
2. QAQC
3. Publish Data  
  1. Enter data
  2. QAQC
  3. Publish Data

2.2.3 Tabs

Use {.tabset} and header levels. Sub-headers (exactly one level down) will become tabs.
### Project {.tabset}
#### Part A
#### Part B

2.2.4 Code, Plotting, Captions

2.2.4.1 Code

  • Insert R Chunk
  • Write code in chunk

Inserting R Chunk

data("iris")
summary(iris)
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
##  1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
##  Median :5.800   Median :3.000   Median :4.350   Median :1.300  
##  Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
##  3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
##  Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    :50  
##  versicolor:50  
##  virginica :50  
##                 
##                 
## 

2.2.4.2 Plot

library(ggplot2)
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) + geom_point()

2.2.4.3 Figure options

  • fig.align = “center” “right” “left”
  • fig.asp = ratio of width:height, height is calculated from fig.width*fig.asp
  • fig.margin = TRUE (place figure in figure margin)
  • fig.fullwidth = TRUE (figure is across full width)
  • fig.width
  • fig.height
  • fig.dim = c(8,6) (width, height)
  • fig.link - add a link to the figure
  • fig.cap = figure caption
  • out.width, out.height - specify output size
    • out.width = “50%” (can then include two figures side by side)
    • out.width = 8
  • out.extra - miscellaneous
    • out.extra = ‘angle=90’

2.2.4.4 Image caption

A normal paragraph.

A scatterplot of the data iris using ggplot. A scatterplot of the data `cars` using **base** R graphics. 

```
{r iris-fig, fig.cap='A scatterplot of the data iris using ggplot.'}
plot(cars)  # a scatterplot
```

A normal paragraph.

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()
A scatterplot of the data iris using ggplot.

Figure 2.1: A scatterplot of the data iris using ggplot.

2.3 Tables

Use kable

library(knitr)
knitr::kable(head(iris), "simple",  caption = "Table with caption")
Table 2.1: Table with caption
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5.0 3.6 1.4 0.2 setosa
5.4 3.9 1.7 0.4 setosa

2.4 Images

![Here are some baby salmon](salmon.jpg)

Here are some baby salmon

2.5 In text References

2.5.1 Figure/Table/Chapter

Table: \@ref(tab:iris-table)
Figure: \@ref(fig:iris-fig)
Chapter of this book: \@ref(intro)

See name of figure (iris-fig)

You can label chapter and section titles using `{#label}` after them,  
e.g., we can reference Chapter \@ref(intro).   
If you do not manually label them, there will be automatic labels anyway,  
e.g., Chapter \@ref(RCoding).
  • See table: 2.1
  • See figure: 2.1
  • Go to intro: 1

2.5.2 Citations

You can write citations, too. For example, we are using the bookdown package (Xie 2020) in this sample book, which was built on top of R Markdown and knitr (Xie 2015).

3 Coding

3.1 Chunks

Use “chunks” for code
Surround by tick marks

```
Code here   
```
## Chunk details

See 2 for more info

3.2 Chunk details

Value What it does
eval whether to evaluate the code
echo whether to display code along with its results
warning whether to display warnings
error whether to display errors
message whether to display messages
tidy whether to reformat code in a tidy way when displaying
results “markup”, “asis”, “hold”, “hide”
cache whether to cache results for future renders
comments comment character to preface results with
fig.width default = 7
fig.height default = 7

4 Interactive tools

4.1 Plotly

Install plotly.

4.1.1 Code

library(plotly)
data("iris")

summary(iris)
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
##  1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
##  Median :5.800   Median :3.000   Median :4.350   Median :1.300  
##  Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
##  3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
##  Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    :50  
##  versicolor:50  
##  virginica :50  
##                 
##                 
## 

4.1.2 Plot

Different ways to code:

plot_ly(iris, x = ~Sepal.Width, y = ~Sepal.Length, type = "scatter", 
        hoverinfo = "text",
        text = ~paste('</br> Species: ', Species,
                      '</br> Petal Length: ', Petal.Length,
                      '</br> Petal Width: ', Petal.Width))
iris %>%
  plot_ly(x = ~Sepal.Length, y = ~Petal.Length) %>%
  add_lines()
p <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) + facet_wrap(~Species) +  geom_point()
ggplotly(p)

4.2 Leaflet

Install leaflet.

library(leaflet)
library(viridis)
library(lubridate)
Stations <- read.csv("StationsMetadata.csv")
summary(Stations)
##    Station          StationName        StartDateDataset   EndDateDataset    
##  Length:138         Length:138         Length:138         Length:138        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##     Agency             Latitude       Longitude      HydrologicArea    
##  Length:138         Min.   :37.65   Min.   :-122.1   Length:138        
##  Class :character   1st Qu.:37.84   1st Qu.:-121.7   Class :character  
##  Mode  :character   Median :38.04   Median :-121.6   Mode  :character  
##                     Mean   :38.02   Mean   :-121.6                     
##                     3rd Qu.:38.16   3rd Qu.:-121.5                     
##                     Max.   :38.79   Max.   :-121.1                     
##     Basin              County          HabitatType       
##  Length:138         Length:138         Length:138        
##  Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character  
##                                                          
##                                                          
## 
Station2 <- Stations %>%
  mutate(Year1 = year(as.Date(StartDateDataset, format = "%m/%d/%Y")),
         Year2 = year(as.Date(EndDateDataset, format = "%m/%d/%Y")),
         Range = Year2-Year1)

Make map - Color by factor

# Palette from viridis
  staPal <- colorFactor("viridis", domain = Stations$Agency)
  
Stations %>% # name of data
  leaflet() %>%
  addTiles() %>%
  addCircleMarkers(
    color = ~staPal(Agency),
    stroke = FALSE,
    fillOpacity = 0.9,
    lng = ~Longitude,
    lat = ~Latitude,
    labelOptions = labelOptions(noHide = F),
    popup = ~paste(Station, ":", StationName, "<br/>",
                   "Agency:", Agency)) %>%
    addLegend(pal = staPal,
            values = ~Agency,
            position = "bottomright")

Make map - size and color by numeric

staPal2 <- colorNumeric("viridis", domain = Station2$Range)

Station2 %>%
  leaflet() %>%
  addTiles() %>%
  addCircleMarkers(
    color = ~staPal2(Range),
    radius = ~Range,
    stroke = FALSE,
    fillOpacity = 0.5,
    lng = ~Longitude,
    lat = ~Latitude,
    labelOptions = labelOptions(noHide = F),
    popup = ~paste(Station, ":", StationName, "<br/>",
                   "Agency:", Agency)) %>%
    addLegend(pal = staPal2,
            values = ~Range,
            position = "bottomright")

References

4.5 Plotly Annotations and Labels

4.7 Example Book

Xie, Yihui. 2015. Dynamic Documents with R and Knitr. 2nd ed. Boca Raton, Florida: Chapman; Hall/CRC. http://yihui.org/knitr/.

———. 2020. Bookdown: Authoring Books and Technical Documents with R Markdown. https://github.com/rstudio/bookdown.